package com.kx.demo.concurrent;

import java.util.LinkedList;

/**
 * @author kx
 */
public class MyQueue {

    private static final int MAX_SIZE = 100;

    private LinkedList<String> queue = new LinkedList<>();

    public synchronized void offer(String element) {
        try {
            if (queue.size() == MAX_SIZE) {
                // 让线程进入等待状态, 已经释放锁
                wait();
            }
            queue.addLast(element);
            notifyAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized String take() {
        String element = null;
        try {
            if (queue.size() == 0) {
                wait();
            }
            element = queue.removeFirst();
            // 唤醒当前在等待这个锁的那些线程
            notifyAll();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return element;
    }

}
